import traceback
from flask import request,Blueprint
from sqlalchemy import func, and_
from sqlalchemy.sql.operators import exists
import  models
from urllib.parse import quote
import json
from werkzeug.serving import WSGIRequestHandler
WSGIRequestHandler.protocol_version = "HTTP/1.1"
from werkzeug.utils import secure_filename
from config import debug, log as log
from config import makeNewSession as makeNewSession
from API.messageAPI import get_group_list,set_group_leave,get_group_info

groups = Blueprint('groups',__name__)


# 获取群聊数据指定分页
@groups.route("/groupData")
def groupData():
    curPage = request.args.get("page",1,type=int)
    per_page = request.args.get("limit",15,type=int)
    getData = json.loads(request.args.get("searchParams","{}"))
    print(getData, bool(getData),"text",getData)
    session = makeNewSession()
    if getData:
        condition = and_(
            models.Group.gid.contains(getData.get("gid",0)),
            models.Group.groupName.contains(getData.get("groupName",'')),
            # models.Group.numbers.contains(getData.get("numbers",'')),
            models.Group.status.contains(getData.get("status",'')),
            models.Group.beizhu.contains(getData.get("beizhu",''))
        )

    # 分页
    all_ = session.query(models.Group).offset((curPage-1)*per_page).limit(per_page)   if not getData else session.query(models.Group).filter(condition).offset((curPage-1)*per_page).limit(per_page)  

    # count  = session.query(func.count(all_)).scalar()
    # 获取总条数
    count =session.query(func.count(models.Group.gid)).scalar() if not getData else session.query(func.count(models.Group.gid)).filter(condition).scalar()

    groupList = get_group_list()
    groupDict = {}
    if groupList:
        # print("groupList",groupList)
        for each in groupList:
            # print("each",each, type(each))
            groupDict[each["group_id"]]=dict(numbers=each["member_count"],groupName=each["group_name"])
    result = {
        "code": 0,
        "msg": "",
        "count": count,
        "data": []
        }
    flag = False
    for each in all_:
        print(each.to_json())
        print(groupDict)
        each = each.to_json()
        if each["gid"] in groupDict: 
            if each["status"] != "已加入":
                each["status"] = "已加入"
                each["numbers"] = groupDict[each['gid']]['numbers']
                # session.execute(f"update ugroups set status = '已加入', numbers='{groupDict[each['gid']]['numbers']}' where gid={each['gid']}")
                session.query(models.Group).filter(models.Group.gid==each['gid']).update(each)
                flag = True
            if each["numbers"] != groupDict[each['gid']]['numbers']:
                session.query(models.Group).filter(models.Group.gid==each['gid']).update(each)
                flag = True

            
        else: 
            if each["status"] != "未加入":
                each["status"] = "未加入"
                each["numbers"] = groupDict[each['gid']]['numbers']
                # session.execute(f"update ugroups set status = '未加入', numbers='{groupDict[each['gid']]['numbers']}' where gid={each['gid']}")
                session.query(models.Group).filter(models.Group.gid==each['gid']).update(each)
                flag = True
        result['data'].append(each)
    # print(each)
    result = json.dumps(result,ensure_ascii=False)
    if flag:session.commit()
    session.close()
    return result


# 删除群组数据
@groups.route("/delGroupData",methods=["POST"])
def delGroupData():
    getData = request.get_json()
    if not getData: return "you need post some args!",406
    session = makeNewSession()
    try:
        # 机器人退出群聊
        set_group_leave(getData['gid'])
        session.query(models.Group).filter(models.Group.gid==getData['gid']).delete()
        session.commit()
        session.close()
        return "del successfully"
    except:
        session.rollback()
        session.close()
        return "del failure",500
# 删除群组数据 多条
@groups.route("/delGroupsData",methods=["POST"])
def delGroupsData():
    getDatas = request.get_json()
    # print(getDatas)
    session = makeNewSession()
    try:
        session.query(models.Group).filter(models.Group.gid.in_(getDatas)).delete()
        session.commit()
        session.close()
        return "del successfully"
    except:
        session.rollback()
        session.close()
        return "del failure",500
# 更新群组数据
@groups.route("/updateGroupData",methods=["POST"])
def updateGroupData():
    getData = request.get_json()
    if not getData: return "you need post some args!",406
    print(getData)
    session = makeNewSession()
    try:
        session.query(models.Group).filter(models.Group.gid==getData["gid"]).update(getData)
        session.commit()
        session.close()
        return "update successfully"
    except:
        session.rollback()
        session.close()
        return "update failure",500


# 添加群聊
@groups.route("/addGroupData", methods=["POST"])
def addGroupData():
    getData = request.get_json()
    if not getData: return "you need post some args!",406
    if not isinstance(getData["gid"], int): getData["gid"] = int(getData["gid"])
    session = makeNewSession()
    group_info = get_group_info(getData["gid"],True)
    debug(group_info)
    if group_info:
        if group_info["max_member_count"] != 0: getData["status"]="已加入"
        getData["groupName"] = group_info["group_name"]
        getData["numbers"] = group_info["member_count"]
    try:
        # mapper(models.Group)
        obj = models.Group(**getData)
        print("obj",obj.to_json())
        session.add(obj)
        session.commit()
        session.close()
        return "add group successfully"
    except:
        print(getData,"插入数据库失败")
        traceback.print_exc()
        session.rollback()
        session.close()
        return ("add group failure",500)

# 添加群聊 多个
@groups.route("/addGroupsData",methods=["POST"])
def addGroupsData():
    getDatas = request.get_json()
    session = makeNewSession()
    for data in getDatas:
        try:
            obj = models.Group(**data)
            session.add(obj)
            session.commit()
        except:
            print(data,"插入数据库失败")
            traceback.print_exc()
            session.rollback()
    
    session.close()
    return "add groups successfully"


